import logging
import os
import time
from io import BytesIO

from appium import webdriver
from appium.options.common.base import AppiumOptions
from appium.webdriver.common.appiumby import AppiumBy


def init_logger():
    '''
    初始化日志
    :return:
    '''
    logger = logging.getLogger('my_logger')
    logger.setLevel(logging.DEBUG)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    # 创建日志消息的格式化器
    formatter = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)s - %(message)s')
    # 将格式化器添加到处理器
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    return logger


def init_driver():
    options = AppiumOptions()
    options.load_capabilities({
        "platformName": "Android",
        "appium:platformVersion": "12",
        "appium:automationName": "UiAutomator2",
        "appium:deviceName": "xiaomi",
        "appium:udid": "cmainnkjvgiv5h4h",
        "appium:appPackage": "com.eg.android.AlipayGphone",
        "appium:appActivity": "com.eg.android.AlipayGphone.AlipayLogin",
        "appium:skipUnlock": True,
        "appium:forceAppLaunch": True,
        "appium:noReset": True,
        "appium:ensureWebviewsHavePages": True,
        "appium:nativeWebScreenshot": True,
        ###  命令执行间隔
        "appium:newCommandTimeout": 600,
        ###  减少find命令耗时
        "appium:waitForIdleTimeout": 100,
        "appium:connectHardwareKeyboard": True
    })
    driver = webdriver.Remote("http://127.0.0.1:4723", options=options)
    return driver


from PIL import Image
import numpy as np


def calculate_image_similarity(image1, image2, is_path=True):
    def load_image(img, is_path):
        if is_path:
            return Image.open(img).convert('L')  # 转换为灰度图像
        else:
            return Image.open(BytesIO(img)).convert('L')  # 转换为灰度图像

    # 加载图片
    image1 = load_image(image1, is_path)
    image2 = load_image(image2, is_path)

    # 调整图片大小以确保它们具有相同的尺寸
    image1 = image1.resize((256, 256))
    image2 = image2.resize((256, 256))

    # 将图片转换为 numpy 数组
    image1_array = np.array(image1)
    image2_array = np.array(image2)

    # 计算均方误差 (MSE)
    mse = np.mean((image1_array - image2_array) ** 2)

    # 计算相似度分数，范围从 0 到 1，1 表示完全相同
    similarity_score = 1 / (1 + mse)

    return similarity_score


def get_time(f):
    def inner(*arg, **kwarg):
        s_time = time.time()
        res = f(*arg, **kwarg)
        e_time = time.time()
        print('耗时：{}秒'.format(e_time - s_time))
        return res

    return inner


@get_time
def image_similarity(img1_path, img2_path, threshold=0.9):
    ssim = calculate_image_similarity(img1_path, img2_path)
    # 输出相似度
    print(f"图片相似度：{ssim}")

    # 判断是否发生明显变化
    if ssim < threshold:
        print("图片内容发生明显变化！")
    else:
        print("图片内容相似。")


def create_directory_if_not_exists(directory):
    """文件夹不存在则创建"""
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
            print(f"目录 '{directory}' 已创建")
        else:
            print(f"目录 '{directory}' 已存在")
    except Exception as e:
        print(f"创建目录时发生错误: {e}")
